package com.itheima.web.controller;

import cn.hutool.captcha.LineCaptcha;
import com.itheima.domain.db.Admin;
import com.itheima.web.interceptor.AdminHolder;
import com.itheima.web.manager.AdminManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
public class AdminController {

    @Autowired
    private AdminManager adminManager;

    //返回校验码图片
    @GetMapping("/system/users/verification")
    public void getVerification(String uuid, HttpServletResponse response) throws IOException {
        //1.调用manager生成验证码图片
        LineCaptcha lineCaptcha =adminManager.getVerification(uuid);
        //hsz勇敢牛牛！
        //2.将验证码返回给浏览器
        response.setContentType("image/jpeg");
        lineCaptcha.write(response.getOutputStream());
    }

    //登录
    @PostMapping("/system/users/login")
    public Map<String, String> login(@RequestBody Map<String,String> map){
        //1.接受参数
        String username = map.get("username");
        String password = map.get("password");
        String verificationCode = map.get("verificationCode");
        String uuid = map.get("uuid");

        //2.调用manager登录，并返回token
        String token = adminManager.login(username,password,verificationCode,uuid);
        //3. 返回map
        HashMap<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        return tokenMap;
    }

    //获取管理员个人信息
    @PostMapping("/system/users/profile")
    public Map<String,String> findAdminInfo(){
        Admin admin = adminManager.findByUsername(AdminHolder.getAdmin().getUsername());

        //3.组装返回一个map(包含uid，username，avatar)
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("uid",admin.getId() + "");
        resultMap.put("username",admin.getUsername());
        resultMap.put("avatar",admin.getAvatar());
        return resultMap;
    }

    //管理员退出
    @PostMapping("/system/users/logout")
    public void logout(@RequestHeader("Authorization") String token){
        token = token.replaceAll("Bearer ", "");
        adminManager.logout(token);
    }


}
